package repositorys

import (
	"github.com/zhongshaofa/swan-jobs/internal/models"
	"github.com/zhongshaofa/swan-jobs/internal/plugin"
)

type ApplicationClientGather struct {
	Appid    int
	ClientId int
	Client   *models.Client
}

type ApplicationClientInterface interface {
	GetList(appIds []int) ([]*ApplicationClientGather, error)
}

type ApplicationClientRepository struct {
}

func (ApplicationClientRepository) GetList(appIds []int) ([]*ApplicationClientGather, error) {
	var list []*models.ApplicationClient
	result := plugin.DB.Where("app_id IN ?", appIds).Order("id asc").Find(&list)
	if result.Error != nil {
		return nil, result.Error
	}
	var gatherList []*ApplicationClientGather
	if result.RowsAffected == 0 {
		return gatherList, nil
	}
	var clientIds []int
	for _, applicationClient := range list {
		clientIds = append(clientIds, applicationClient.ClientId)
		applicationClientGather := &ApplicationClientGather{
			Appid:    applicationClient.AppId,
			ClientId: applicationClient.ClientId,
		}
		gatherList = append(gatherList, applicationClientGather)
	}

	var clientList []*models.Client
	clientResult := plugin.DB.Find(&clientList, clientIds)
	if clientResult.Error != nil {
		return nil, clientResult.Error
	}

	for index, gather := range gatherList {
		for _, client := range clientList {
			if int(client.ID) == gather.ClientId {
				gather.Client = client
				break
			}
		}
		gatherList[index] = gather
	}

	return gatherList, nil
}
